package com.lkd.job;

import com.lkd.common.VMSystem;
import com.lkd.entity.UserEntity;
import com.lkd.service.UserService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>Description: 每日初始化员工分数</p>
 * 
 * @author liuyiming
 * @date 2022-12-18 19:47
 * @version 1.0.0
 */
@Component
@Slf4j
public class UserJob {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @XxlJob("workCountInitJobHandler")
    public ReturnT<String> workCountInitJobHandler(String param) {
        List<UserEntity> userEntityList = userService.list();

        //1.先查询出所有工作人员
        for (UserEntity userEntity : userEntityList) {
            //2.循环存入redis并设置过期时间为1天（管理员除外）  key:前缀_日期_区域_角色code   value:用户ID
            if (VMSystem.ADMIN_ROLE_CODE.equals(userEntity.getRoleCode())) continue;
            //key：前缀_日期_区域_角色code
            String redisKey = VMSystem.REGION_TASK_KEY_PREF
                    + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                    + "." + userEntity.getRegionId()
                    + "." + userEntity.getRoleCode();
            //放入redis中
            redisTemplate.opsForZSet().add(redisKey,userEntity.getId(),0);
            //设置过期时间
            redisTemplate.expire(redisKey,Duration.ofDays(1));
        }
        return ReturnT.SUCCESS;
    }
}
